﻿using System;
using System.IO;
using ParserGenerator.Input;
using ParserGenerator.Output;
using ParserGenerator.SyntacticAnalysis;

namespace ParserGenerator.GrammarConstruction
{
    [Serializable]
    public sealed class LexicalPrecedence
    {
        public GrammarTerminalSymbol Left { get; }
        public LexicalPrecedenceOperator Op { get; }
        public GrammarTerminalSymbol Right { get; }
        public SourceContext Context { get; }

        internal LexicalPrecedence(GrammarTerminalSymbol left, LexicalPrecedenceOperator op, GrammarTerminalSymbol right)
            : this(left, op, right, null)
        {
        }

        internal LexicalPrecedence(GrammarTerminalSymbol left, LexicalPrecedenceOperator op, GrammarTerminalSymbol right, SourceContext context)
        {
            if (left == null)
                throw new ArgumentNullException(nameof(left));
            if (right == null)
                throw new ArgumentNullException(nameof(right));
            Left = left;
            Op = op;
            Right = right;
            Context = context;
        }

        private static string FormatOp(LexicalPrecedenceOperator op)
        {
            using (StringWriter writer = new StringWriter())
            {
                IndentedWriter w = new IndentedWriter(writer);
                SyntaxTreeNodeWriter.Instance.WriteLexicalPrecedenceOperator(op, w);
                return writer.ToString().Trim();
            }
        }

        public sealed override string ToString()
        {
            return Left + " " + FormatOp(Op) + " " + Right;
        }
    }
}
